package com.xhwy.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.xhwy.entity.OrderDetail;
import com.xhwy.mapper.OrderDetailMapper;
import com.xhwy.param.OrderParam;
import com.xhwy.service.AlipayService;
import com.xhwy.service.OrderService;
import com.xhwy.enums.OrderState;
import com.xhwy.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Date;

@Service
@Slf4j
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private Environment config;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    /**
     * 交易支付
     *
     * @return
     */
    @Transactional //开启事务
    @Override
    public String tradePay(OrderParam orderParam) {
        try {

            //生成订单
            R r = orderService.save(orderParam);
            OrderDetail orderDetail = (OrderDetail) r.get("data");


            //调用支付宝接口
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            //配置需要的公共请求参数
//            request.setNotifyUrl(config.getProperty("alipay.notify-url"));
            //设置支付完成跳转的页面
            request.setReturnUrl(config.getProperty("alipay.return-url"));
            request.setReturnUrl(config.getProperty("alipay.return-url") + "?orderDetailId=" + orderDetail.getOrderDetailId());

            //组装当前业务方法的请求参数
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderDetail.getOrderDetailId());
//            BigDecimal totalAmount = new BigDecimal(orderInfo.getTotalFee().toString()).divide(new BigDecimal("100"));
            bizContent.put("total_amount", orderDetail.getTotalPayment());
            bizContent.put("subject", orderDetail.getTitle());
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
    //bizContent.put("time_expire", "2022-08-01 22:00:00");

    //// 商品明细信息，按需传入
    //JSONArray goodsDetail = new JSONArray();
    //JSONObject goods1 = new JSONObject();
    //goods1.put("goods_id", "goodsNo1");
    //goods1.put("goods_name", "子商品1");
    //goods1.put("quantity", 1);
    //goods1.put("price", 0.01);
    //goodsDetail.add(goods1);
    //bizContent.put("goods_detail", goodsDetail);

    //// 扩展信息，按需传入
    //JSONObject extendParams = new JSONObject();
    //extendParams.put("sys_service_provider_id", "2088511833207846");
    //bizContent.put("extend_params", extendParams);

            request.setBizContent(bizContent.toString());
            //执行请求，调用支付宝接口
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            if(response.isSuccess()){
                //修改订单状态和付款时间
                orderDetailMapper.updateOrderStateAndPaymentTime(orderDetail.getOrderDetailId(),OrderState.WAITDELIVER.getStateCode(),new Timestamp(new Date().getTime()));
                log.info("调用成功，返回结果==》" + response.getBody());
                return response.getBody();
            } else {
                log.info("调用失败，返回码==》" + response.getCode() + "，返回描述==>" + response.getMsg());
                throw new RuntimeException("交易支付失败");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException("交易支付失败");
        }
    }
}
